#include "dstructs.h"


void pcap_callback (u_char *args, const struct pcap_pkthdr *pkthdr, const u_char *packet){
  
  test* myargs = (test*) args;
  myargs->ether = (struct ether_header *)packet;
  myargs->iphdr = (struct nread_ip*)(packet + sizeof(struct ether_header));
  myargs->tcphdr = (struct nread_tcp*)(packet + sizeof(struct ether_header) + sizeof(struct nread_ip));
  char sqlstr[1024];
  char ipsrc[20],ipdst[20];

  //Some of the printf line are for debugging only
  //printf("%u",myargs->ether->ether_type);
  
  if (ntohs (myargs->ether->ether_type) == ETHERTYPE_IP){
        if(myargs->iphdr->ip_p == IPPROTO_TCP){
    
	  double milsec = pkthdr->ts.tv_usec;
	  double ptime = pkthdr->ts.tv_sec + (milsec/1000000);
     //still undecided how to log fragmentation
 	  //printf("%x Offset ",ntohs(myargs->iphdr->ip_off));
	  //printf("%x DF :",(myargs->iphdr->ip_off & htons(IP_DF)));
	  //printf("%x MF:",(myargs->iphdr->ip_off & htons(IP_MF)));
	  //printf("%x OFFMASK\n",(myargs->iphdr->ip_off & htons(IP_OFFMASK)));
	  sprintf(ipsrc,"%s",inet_ntoa(myargs->iphdr->ip_src));
	  sprintf(ipdst,"%s",inet_ntoa(myargs->iphdr->ip_dst));
  
	  //------------------------------(**event**)(************************ip***************************)(**********tcp**************************************)(****frame****)
	  sprintf (sqlstr,"CALL insert_row('%f','%f','%f','%s','%s','%x','%x','%u','%u','%x','%u','%u','%u','%x','%f','%d','%d','%u','%u','%02X','%u','%u','%x','%2x','%f','%s','%s')",
	      ptime,ptime,
	   
	      ptime,ipsrc,ipdst,(IP_V(myargs->iphdr)),(IP_HL(myargs->iphdr)*4),
	      myargs->iphdr->ip_tos, ntohs(myargs->iphdr->ip_len), ntohs(myargs->iphdr->ip_off), myargs->iphdr->ip_ttl,
              myargs->iphdr->ip_p, myargs->iphdr->ip_sum,htons(myargs->iphdr->ip_id),
	   
	      ptime,ntohs(myargs->tcphdr->th_sport),ntohs(myargs->tcphdr->th_dport),ntohl(myargs->tcphdr->th_seq),ntohl(myargs->tcphdr->th_ack),
	      myargs->tcphdr->th_flags,myargs->tcphdr->th_win,myargs->tcphdr->th_urp,ntohs(myargs->tcphdr->th_sum),(myargs->tcphdr->th_off<<4),
	   
	      ptime,eth_ntoa((struct ether_adr*)myargs->ether->ether_shost),eth_ntoa((struct ether_adr*)myargs->ether->ether_dhost)	   
	    );
   
	  if (mysql_query(myargs->conn,sqlstr)) {
	    printf("Error %u: %s\n", mysql_errno(myargs->conn), mysql_error(myargs->conn));
	    exit(1);
	  }		
	  pcap_dump((u_char *)myargs->dumpfile,pkthdr,packet);
	  }
      }
} //end pcap_callback